<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>2.bridge典型应用之ajax请求</title>
</head>
<body>
    <lebal for="username">帐号</lebal>
    <input type="text" id="username" placeholder="请输入帐号" name="username"/> <br>
    <lebal for="password">密码</lebal>
    <input type="text" id="password" placeholder="请输入密码" name="password"/><br>
    <lebal for="password">id</lebal>
    <input type="text" id="id" placeholder="请输入id" name="id"/><br>
    <button id="submitBtn">提交</button>
    <div class="serverRes">

    </div>
    <script>
        function InputValue(arr) { 
            let data = {};
            if (arr.length > 0) {
                arr.forEach(element => {
                    let item = document.querySelector('#' + element);
                    let value = item.value;
                    if (!value) {
                        return alert('表单不能为空');
                    } else {
                        data[item.name] = value;
                    }
                });
            }
            console.log('data:', data);
            return data
        };
        document.querySelector("#submitBtn").onclick = function () { 
            let arr = ['username', 'password', "id"];
            let res = InputValue(arr);
            ajaxFn(res, function (res) { 
                console.log('ajax请求返回的是：', res, document.querySelector('.serverRes'));
                document.querySelector('.serverRes').innerHTML = res;
             });
         }

         function ajaxFn(data, callback) { 
             if (!data.id) return;
             let xhr = new XMLHttpRequest();
             xhr.open('GET', 'http://localhost:8080/user/' + data.id);
             xhr.send();
             xhr.onload = function () { 
                 if (xhr.status == 200 && xhr.readyState == 4) {
                    callback(xhr.responseText);
                 }
              }
          }
    </script>
</body>
</html>